import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {getProperty, MessageService, ModalComponent, PaginationService, Table} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {Router} from '@angular/router';
import {HttpParams} from '@angular/common/http';
import {RobotEditComponent} from '../robot-edit/robot-edit.component';
import {RobotProduceComponent} from '../robot-produce/robot-produce.component';
import {RobotManagerFormatterService} from '../../../../services/formatter/robot-manager.service';
import {timer} from 'rxjs';

@Component({
  selector: 'robot-manager',
  templateUrl: './robot-manager.component.html',
  styleUrls: ['./robot-manager.component.scss']
})
export class RobotManagerComponent implements OnInit, AfterViewInit {
  @ViewChild('modal') private modal: ModalComponent;
  breadcrumb = [
    {name: '机器人管理', cssIcon: 'fa fa-fw fa-reddit-alien'}
  ];
  page = 1;
  editRobotData;
  deleteRobotData;
  pagenation = new PaginationService(null, null);
  chargeTable = new Table({
    headers: this.robotGroupFormatter.formatter,
    buttons: [
      {
        btnClass: 'btn btn-danger btn-sm mr-1 px-1 py-0',
        iconClass: 'fa fa-fw fa-pencil-square',
        text: '编辑',
        isShow: true,
        click: (e) => {
          this.editRobotData = e;
          this.showEditRobot();
        }
      },
      {
        btnClass: 'btn btn-danger btn-sm mr-1 px-1 py-0',
        iconClass: 'fa fa-fw fa-trash',
        text: '删除',
        isShow: true,
        click: (e) => {
          this.deleteRobotData = e;
          this.showDeleteRobot();
        }
      }
    ]
  });

  constructor(private message: MessageService,
              private ticketService: TicketService,
              private router: Router,
              private robotGroupFormatter: RobotManagerFormatterService,
  ) {
  }

  ngOnInit() {
    this.getInfo(1);
    this.getAvatar();

  }
  produceRobot() {
    this.modal.show({
      title: '生成机器人',
      cssIcon: 'fa fa-fw fa-plus-circle',
      dynamicComponent: {
        component: RobotProduceComponent,
        events: {
          success: () => {
            this.modal.hide();
            this.getInfo(this.page);
          }
        },
      },
      data: null
    });
  }
  showEditRobot() {
    this.modal.show({
      title: '编辑机器人',
      cssIcon: 'fa fa-fw fa-pencil-square',
      dynamicComponent: {
        component: RobotEditComponent,
        data: this.editRobotData,
        events: {
          success: (data) => {
            timer(1000).subscribe(() => {
              this.modal.hide();
              this.getInfo(this.page);
            });
          }
        },
      },
      data: null
    });
  }
  showDeleteRobot() {
    const options = {
      id: 'deleteRobot',
      title: '删除机器人',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '数据删除后无法恢复，确定删除？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
  }
  modalEvenHandler() {
    this.modal.event.subscribe({
      next: (event) => {
        if (event.name === 'confirm' && event.id === 'deleteRobot') {
          this.deleteRobot();
        }
      }
    });
  }
  deleteRobot() {
    this.ticketService.post(this.ticketService.urls.delRobot, {userId: this.deleteRobotData.userUid}, {
      observe: 'response',
      params: new HttpParams()
          .append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
      if (resp.body.success) {
        this.modal.hide();
        this.getInfo(this.page);
      }
    });
  }
  getInfo(page) {
    this.pagenation.simpleFormatter = this.chargeTable.options.headers;
    this.ticketService.get(this.ticketService.urls.getAllRobots, {
      observe: 'response',
      params: new HttpParams()
          .append('web_token', localStorage.getItem('token'))
          .append('pageNum', page + '')
          .append('pageSize', '10')}).subscribe((resp) => {
      if (resp.body.success) {
        const result = resp.body.returnValue.page;
        const paginationResult = [];
        for (const item of result.list) {
          item.userImage = this.ticketService.serverConfig.httpServer + this.ticketService.baseUrl + this.ticketService.urls.userAvatarDownloader + '?action=ad&user_uid=' + item.userUid + '&enforceDawnload=1';
          paginationResult.push(item);
        }
        this.pagenation.page.results = paginationResult;
        this.pagenation.page.totalPage = result.pages;
        this.pagenation.page.pageNumber = result.pageNum;
        this.pagenation.formatData();
        this.message.sendMessage('page load progress', this);
      } else {
        this.router.navigateByUrl('/login').catch();
      }
    });
  }
  get getProperty() {
    return getProperty;
  }
  getAvatar() {
    this.ticketService.get(this.ticketService.urls.userAvatarDownloader, {
      observe: 'response',
      params: new HttpParams()
        .append('web_token', localStorage.getItem('token'))
        .append('action', 'ad')
        .append('user_uid', '51942797')
        .append('enforceDawnload', '1')}).subscribe((resp) => {
    });
  }
  firstPage() {
    this.page = 1;
    this.getInfo(1);
  }
  previousPage() {
    if (this.page > 1) {
      this.page = this.page - 1;
    } else {
      this.page = 1;
    }
    this.getInfo(this.page);
  }
  nextPage() {
    if (this.page < this.pagenation.page.totalPage) {
      this.page = this.page + 1;
    } else {
      this.page = this.pagenation.page.totalPage;
    }
    this.getInfo(this.page);
  }
  lastPage() {
    this.page = this.pagenation.page.totalPage;
    this.getInfo(this.pagenation.page.totalPage);
  }
  ngAfterViewInit(): void {
    this.modalEvenHandler();
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
    this.message.sendMessage('page load progress', this, '300ms');
  }

}
